package com.example.yibu.futuresDemoTest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

public class APPlyExample {
//异步处理任务
/*
    public static void main(String[] args) {
        futuresDemo();
    }
*/
    public static void futuresDemo(){
        try {
            long timeMillis = System.currentTimeMillis();
            List<CompletableFuture<String>> futures = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                String upId = String.valueOf(i);
                futures.add(CompletableFuture.supplyAsync(() ->
                        handleDemo(upId)
                ));
            }
            // 使用allOf等待所有任务完成，然后使用thenApply处理结果
            CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
            CompletableFuture<List<Object>> resultsFuture = allFutures.thenApply(v ->
                    futures.stream().map(CompletableFuture::join).collect(Collectors.toList())
            );

            // 获取处理后的结果列表
            List<Object> results = null;
            try {
                results = resultsFuture.get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
            long timeMillis1 = System.currentTimeMillis();
            System.out.println("运行时间(秒)为: " + (timeMillis1 - timeMillis) / 1000);
            System.out.println(results); // 输出
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String handleDemo(String id){
        try {
            String json = "ABCDEFG : " + id;
            Thread.sleep(5000);
            return json;
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

}
